import { defineStore } from 'pinia';
import { mitt, timer, getSystemInfo, createDeferred } from '@jecloud/utils';
import { loadMicroApp } from '../data/api/micro';
import MicroApp from '../data/model/micro-app';
import { MicroActiveType } from '../data/enum/micro';
import { loadDynamicApp } from '@/hooks/use-micro';
/**
 * 主应用store
 */
export const useAdminStore = defineStore({
  id: 'admin-store',
  state: () => ({
    init: false,
    appConfig: new Map(),
    apps: new Map(),
    emitter: mitt(),
  }),
  actions: {
    /**
     * 绑定主应用事件，供子应用触发调用
     * @param args
     */
    on(...args) {
      this.emitter.on(...args);
    },
    /**
     * 触发主应用事件，供子应用触发调用
     * @param args
     */
    emit(...args) {
      return this.emitter.emit(...args);
    },
    /**
     * 触发微应用事件
     * @param args
     */
    emitMicroAll(...args) {
      Array.from(this.apps.keys()).forEach((name) => {
        this.emitMicro(name, ...args);
      });
    },
    /**
     * 触发微应用事件
     * @param args
     */
    emitMicro(name, eventName, ...args) {
      const config = this.appConfig.get(name);
      const activeType = config?.activeType;
      // 动态微应用加载
      if ([MicroActiveType.PLUGIN].includes(activeType)) {
        return loadDynamicApp(name).then(() => {
          const app = this.apps.get(name)?.get(activeType);
          return this.emitPromiseEvent(app, eventName, ...args);
        });
        // 初始化插件
      } else if ([MicroActiveType.INIT].includes(activeType)) {
        const app = this.apps.get(name)?.get(activeType);
        return this.emitPromiseEvent(app, eventName, ...args);
      } else if (this.apps.has(name)) {
        // 菜单
        const appMap = this.apps.get(name);
        Array.from(appMap?.values()).forEach((layoutApp) => {
          layoutApp.emit(eventName, ...args);
        });
      }
    },
    /**
     * 异步事件执行
     * @param {*} app
     * @param {*} eventName
     * @param  {...any} args
     * @returns
     */
    emitPromiseEvent(app, eventName, ...args) {
      const deferred = createDeferred();
      // 未初始化
      let count = 10;
      // 加入延迟循环，处理事件，超过10次，停止循环
      const t = timer(() => {
        if (app?.emitter.listeners.has(eventName)) {
          const result = app.emit(eventName, ...args);
          deferred.resolve(result);
          return false;
        } else if (count === 0) {
          console.log('微应用事件不存在', {
            code: '404',
            app: app?.options,
            eventName,
            params: args,
          });
          deferred.resolve();
          return false;
        } else {
          count--;
        }
      }, 100);
      t.exec();
      return deferred.promise;
    },
    /**
     * 获得微应用name
     * @param {*} param0
     * @returns
     */
    getMicroName({ name, layout }) {
      return layout ? `${name}_${layout}` : name;
    },
    /**
     * 注册微应用
     * @param {*} name
     * @param {*} app
     */
    setupMicro({ name, layout, store }) {
      if (!this.apps.has(name)) {
        this.apps.set(name, new Map());
      }
      const app = this.apps.get(name);
      app.set(layout, store);
    },
    /**
     * 销毁微应用
     * @param {*} name
     */
    destroyMicro({ name, layout }) {
      const app = this.apps.get(name);
      const layoutApp = app?.get(layout);
      layoutApp?.destroy();
      app?.delete(layout);
    },
    /**
     * 登录
     */
    login() {
      this.init = true;
      // 共享系统数据，防止子应用再次请求
      const systemInfo = getSystemInfo();
      this.emit('login-success', systemInfo);
      this.emitMicroAll('admin-login-success', systemInfo);
    },
    /**
     * 注销
     */
    logout() {
      this.init = false;
      this.emit('logout');
      this.emitMicroAll('admin-logout');
    },
    /**
     * 是否包含微应用配置
     * @param {*} name
     * @returns
     */
    hasMicroConfig(name) {
      return this.appConfig.has(name);
    },
    /**
     * 获取微应用配置
     * @param {*} name
     * @returns
     */
    getMicroConfig(name) {
      return this.appConfig.get(name);
    },
    /**
     * 获取微应用配置-菜单
     * @returns
     */
    getMicroConfig4Menu() {
      return Array.from(this.appConfig.values()).filter(
        (app) => app.activeType === MicroActiveType.MENU,
      );
    },
    /**
     * 获取微应用配置-登录
     * @returns
     */
    getMicroConfig4Login() {
      return Array.from(this.appConfig.values()).find(
        (app) => app.activeType === MicroActiveType.LOGIN,
      );
    },
    /**
     * 获取微应用配置-初始化
     * @returns
     */
    getMicroConfig4Init() {
      return Array.from(this.appConfig.values()).filter(
        (app) => app.activeType === MicroActiveType.INIT,
      );
    },
    /**
     * 初始app信息
     * @returns
     */
    initMicroConfig() {
      if (this.appConfig.size) {
        return Promise.resolve();
      } else {
        return loadMicroApp().then((data) => {
          data.forEach((item) => {
            // TODO:此处可以调试微应用，仅供开发使用
            // if (item.MICROAPP_CODE === 'JE_CORE_LOGIN') {
            //   item.MICROAPP_ENTRY = 'http://localhost:3001/micro/login/';
            // }
            const app = new MicroApp(item);
            this.appConfig.set(app.name, app);
          });
        });
      }
    },
  },
});
